export class NativePopup {
  constructor(options = {}) {
    this.sysInfo = uni.getSystemInfoSync();

    const { bgColor = '#ffffff', titleColor = '#000000', contentColor = '#727687' } = options;

    this.bgColor = bgColor;
    this.titleColor = titleColor;
    this.contentColor = contentColor;
  }

  createPopup = () => {
    const popupView = new plus.nativeObj.View('popupView', {
      top: '50px',
      left: 0,
      width: '100%',
      height: '95px'
    });

    popupView.addEventListener('click', this.close);

    const bgPadding = 15;

    popupView.drawRect(
      {
        color: '#e6e6e6',
        radius: '8px'
      },
      {
        top: '4px',
        left: bgPadding - 1 + 'px',
        width: this.sysInfo.screenWidth - bgPadding * 2 + 2 + 'px',
        height: '87px'
      }
    );

    popupView.drawRect(
      {
        color: this.bgColor,
        radius: '8px'
      },
      {
        top: '5px',
        left: bgPadding + 'px',
        width: this.sysInfo.screenWidth - bgPadding * 2 + 'px',
        height: '85px'
      }
    );

    popupView.drawText(
      this.title,
      {
        top: '10px',
        left: bgPadding + 10 + 'px',
        height: '30px'
      },
      {
        size: '16px',
        weight: 'bold',
        align: 'left',
        color: this.titleColor
      }
    );

    popupView.drawText(
      'X',
      {
        top: '10px',
        right: bgPadding + 10 + 'px',
        height: '30px'
      },
      {
        size: '16px',
        align: 'right',
        color: '#666666'
      }
    );

    popupView.drawText(
      this.content,
      {
        top: '40px',
        height: '40px',
        left: bgPadding + 10 + 'px',
        width: this.sysInfo.screenWidth - bgPadding * 2 - 20 + 'px'
      },
      {
        size: '14px',
        align: 'left',
        color: this.contentColor,
        whiteSpace: 'normal'
      }
    );

    this.popupView = popupView;

    return popupView;
  };

  show = (options = {}) => {
    this.close();

    const { title = '权限申请说明', content = '' } = options;
    this.title = title;
    this.content = content;

    this.createPopup();

    this.popupView.show();
  };

  close = () => {
    this.popupView && this.popupView.close();
  };
}

export const popup = new NativePopup();
